package cn.eeepay.framework.service.workOrder.impl;

import cn.eeepay.framework.dao.TeamInfoDao;
import cn.eeepay.framework.dao.workOrder.WorkCensusReadDao;
import cn.eeepay.framework.dao.workOrder.WorkWarningReadDao;
import cn.eeepay.framework.db.pagination.Page;
import cn.eeepay.framework.model.TeamInfo;
import cn.eeepay.framework.model.workOrder.*;
import cn.eeepay.framework.service.workOrder.WorkCensusService;
import cn.eeepay.framework.util.DateUtils;
import cn.eeepay.framework.util.ListDataExcelExport;
import cn.eeepay.framework.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WorkCensusServiceImpl implements WorkCensusService {

    private Logger log = LoggerFactory.getLogger(WorkCensusServiceImpl.class);

    @Resource
    private WorkCensusReadDao workCensusReadDao;
    @Resource
    private WorkWarningReadDao workWarningReadDao;

    @Resource
    private TeamInfoDao teamInfoDao;


    /**
     * 投诉总量统计-组织获取
     * @param msg
     */
    @Override
    public void getCountTeamList(Map<String, Object> msg) {
        WorkCensusFilter info=new WorkCensusFilter();
        getQueryTeamList(info,true);
        msg.put("teamAllList",info.getTeamAllList());
        msg.put("status", true);
    }

    /**
     * 投诉总量统计
     * @param info
     * @param page
     * @param msg
     */
    @Override
    public void countTeamWork(WorkCensusFilter info, Page<WorkCensusFilter> page, Map<String, Object> msg) {
        //封装查询条件
        if(encapsulationCondition(info,page,msg)){
            List<Map<String,Object>> list=workCensusReadDao.countTeamWork(info);
            msg.put("list",list);
            msg.put("teamAllList",info.getTeamAllList());
            msg.put("status", true);
        }
    }

    /**
     * 投诉总量统计-汇总
     * @param info
     * @param msg
     */
    public void countTeamWorkCount(WorkCensusFilter info,Map<String, Object> msg) {
        //封装查询条件
        if(encapsulationCondition(info,null,msg)){
            WorkCensusCount countInfo=workCensusReadDao.countTeamWorkCount(info);
            msg.put("countInfo",countInfo);
            msg.put("status", true);
        }
    }

    /**
     * 投诉总量统计-导出
     * @param info
     * @param msg
     */
    @Override
    public void exportTeamWork(WorkCensusFilter info,HttpServletResponse response,Map<String, Object> msg) throws Exception{
        if(encapsulationCondition(info,null,msg)){
            List<Map<String,Object>> list=workCensusReadDao.exportTeamWork(info);

            List<TeamInfoVo> teamAllList=info.getTeamAllList();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss") ;
            String fileName = "投诉总量统计"+sdf.format(new Date())+".xlsx" ;
            String fileNameFormat = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameFormat);
            List<Map<String, String>> data = new ArrayList<Map<String,String>>() ;
            if(list.size()<1){
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("dayDate",null);
                for(int i=0;i<teamAllList.size();i++){
                    TeamInfoVo teamInfo=teamAllList.get(i);
                    String key="team"+teamInfo.getTeamId().replace("-","_");
                    maps.put(key,null);
                }
                maps.put("count",null);
                maps.put("agentCount",null);
                maps.put("linkRelativeRatio",null);
                data.add(maps);
            }else{
                for (Map<String,Object> item : list) {
                    Map<String, String> maps = new HashMap<String, String>();
                    maps.put("dayDate", item.get("dayDate")==null?"":item.get("dayDate").toString());
                    for(int i=0;i<teamAllList.size();i++){
                        TeamInfoVo teamInfo=teamAllList.get(i);
                        String key="team"+teamInfo.getTeamId().replace("-","_");
                        maps.put(key, item.get(key)==null?"":item.get(key).toString());
                    }

                    maps.put("count",item.get("count")==null?"":item.get("count").toString());
                    maps.put("agentCount",item.get("agentCount")==null?"":item.get("agentCount").toString());
                    maps.put("linkRelativeRatio",item.get("linkRelativeRatio")==null?"":item.get("linkRelativeRatio").toString());
                    data.add(maps);
                }
            }
            ListDataExcelExport export = new ListDataExcelExport();
            int length=teamAllList.size()+4;

            String[] cols = new String[length];
            cols[0]="dayDate";
            cols[cols.length-3]="count";
            cols[cols.length-2]="agentCount";
            cols[cols.length-1]="linkRelativeRatio";

            String[] colsName = new String[length];
            colsName[0]="统计日期";
            colsName[colsName.length-3]="合计";
            colsName[colsName.length-2]="涉及服务商";
            colsName[colsName.length-1]="环比(较上月)";

            //动态加载列表
            for(int i=0;i<teamAllList.size();i++){
                TeamInfoVo teamInfo=teamAllList.get(i);
                String key="team"+teamInfo.getTeamId().replace("-","_");
                cols[i+1]=key;
                String keyName="投诉次数("+teamInfo.getTeamName()+")";
                colsName[i+1]=keyName;
            }

            OutputStream ouputStream =null;
            try {
                ouputStream=response.getOutputStream();
                export.export(cols, colsName, data, response.getOutputStream());
            }catch (Exception e){
                log.error("导出投诉总量统计失败!",e);
            }finally {
                if(ouputStream!=null){
                    ouputStream.close();
                }
            }

        }
    }


    /**
     * 封装-投诉总量统计-必须条件
     * @param info
     * @param page
     */
    private boolean encapsulationCondition(WorkCensusFilter info, Page<WorkCensusFilter> page, Map<String, Object> msg){

        if(!StringUtils.isNotBlank(info.getDateStrBegin()) || !StringUtils.isNotBlank(info.getDateStrEnd())){
            msg.put("status", false);
            msg.put("msg", "统计日期不能为空!");
            return false;
        }
        //转换查询时间 00:00:00 000 -23:59:59 000
        Date createTimeBegin= DateUtils.transformationTime(DateUtils.parseDate(info.getDateStrBegin()),1);
        Date createTimeEnd= DateUtils.transformationTime(DateUtils.parseDate(info.getDateStrEnd()),2);
        if(createTimeEnd.getTime() < createTimeBegin.getTime()){
            msg.put("status", false);
            msg.put("msg","结束时间时间不能小于起始时间");
            return false;
        }
        if(createTimeEnd.getTime() - createTimeBegin.getTime() > 180*24*60*60*1000L){
            msg.put("status", false);
            msg.put("msg","统计日期间隔不能超过180天");
            return false;
        }

        //时间筛选 对应上月 00:00:00 000 -23:59:59 000
        Date createTimeMonthBegin= DateUtils.DateAdd(createTimeBegin, Calendar.MONTH,-1);
        Date createTimeMonthEnd= DateUtils.DateAdd(createTimeEnd, Calendar.MONTH,-1);

        info.setCreateTimeBegin(createTimeBegin);
        info.setCreateTimeEnd(createTimeEnd);
        info.setCreateTimeMonthBegin(createTimeMonthBegin);
        info.setCreateTimeMonthEnd(createTimeMonthEnd);

        //获取组织
        getQueryTeamList(info,true);
        if(info.getTeamAllList().size()<=0){
            msg.put("status", false);
            msg.put("msg","统计组织为空");
            return false;
        }
        if(page!=null){
            info.setPageSize(page.getPageSize());
            info.setPageFirst(page.getFirst());
        }
        return true;
    }

    /**
     * 返回代理商符合的组织列表
     * @param info 过滤对象
     * @return
     */
    private int getQueryTeamList(WorkCensusFilter info,boolean flag){

        //主组织
        List<TeamInfoVo> teamlist =new ArrayList<>();
        StringBuffer teamsb=new StringBuffer();

        //子组织
        List<TeamInfoVo> teamEntrylist =new ArrayList<>();
        StringBuffer teamEntrysb=new StringBuffer();

        //全部维度组织
        List<TeamInfoVo> teamAllList =new ArrayList<>();

        //获取统计组织
        WaringConfigInfo switchWork=workWarningReadDao.getWaringConfig();
        if(switchWork!=null){
            if(StringUtils.isNotBlank(switchWork.getTeamIdList())){
                String[] teamIds = switchWork.getTeamIdList().split(",");
                if(teamIds!=null && teamIds.length>0){
                    for (String teamId : teamIds) {
                        TeamInfoVo teamInfo = new TeamInfoVo();
                        teamInfo.setTeamId(teamId);
                        if(flag){
                            TeamInfo tmp = teamInfoDao.selectTeamInfo(Integer.valueOf(teamId));
                            if(tmp!=null){
                                teamInfo.setTeamName(tmp.getTeamName());
                            }
                        }
                        teamlist.add(teamInfo);
                        teamAllList.add(teamInfo);
                        teamsb.append( teamId+",");
                        //判断是否存在子组织
                        List<TeamInfoVo> subs = teamInfoDao.getSubTeamByMainTeamId(teamId);
                        if(subs!=null && subs.size()>0){
                            for (TeamInfoVo sub : subs) {
                                if(StringUtil.strContent(switchWork.getTeamEntryIdList(),sub.getTeamEntryId(),",")){
                                    sub.setTeamId(sub.getTeamEntryId());
                                    sub.setTeamName(sub.getTeamEntryName());
                                    teamEntrylist.add(sub);
                                    teamAllList.add(sub);
                                    teamEntrysb.append( sub.getTeamId()+",");
                                }
                            }
                        }
                    }
                }
            }



            if(StringUtil.isNotBlank(switchWork.getTeamEntryIdList())){
                String[] teamEntryIds = switchWork.getTeamEntryIdList().split(",");
                if(teamEntryIds!=null && teamEntryIds.length>0){
                    for (String teamEntryId : teamEntryIds) {
                        TeamInfoVo sub = teamInfoDao.selectSubTeam(teamEntryId);
                        if(sub!=null){
                            boolean exist = false;
                            for (TeamInfoVo allInfo : teamAllList) {
                                if(sub.getTeamEntryId().equals(allInfo.getTeamId())){
                                    exist = true;
                                    break;
                                }
                            }
                            if(exist){
                                continue;
                            }
                            sub.setTeamId(sub.getTeamEntryId());
                            sub.setTeamName(sub.getTeamEntryName());
                            teamEntrylist.add(sub);
                            teamAllList.add(sub);
                            teamEntrysb.append( teamEntryId+",");
                        }
                    }
                }
            }

        }

        if(teamsb.length()>1){
            teamsb.setLength(teamsb.length()-1);
        }

        if(teamEntrysb.length()>1){
            teamEntrysb.setLength(teamEntrysb.length()-1);
        }


        info.setTeamList(teamlist);
        info.setTeamStr(teamsb.toString());

        info.setTeamEntryList(teamEntrylist);
        info.setTeamEntryStr(teamEntrysb.toString());

        info.setTeamAllList(teamAllList);
        return 1;
    }


    /**
     * 下级代理商被投诉排名
     * @param info
     * @param page
     * @param msg
     */
    @Override
    public void countAgentWork(WorkCensusFilter info, Page<WorkCensusFilter> page, Map<String, Object> msg) {
        //封装查询条件
        if(encapsulationConditionAgent(info,page,msg)){
            List<WorkCensusAgentInfo> list=workCensusReadDao.countAgentWork(info);
            msg.put("list",list);
            msg.put("status", true);
        }

    }

    /**
     * 下级代理商被投诉排名
     * @param info
     * @param page
     * @param msg
     */
    @Override
    public void countAgentWork2(WorkCensusFilter info, Page<WorkCensusFilter> page, Map<String, Object> msg) {
        //封装查询条件
        if(encapsulationConditionAgent(info,page,msg)){
            List<WorkCensusAgentInfo> list=workCensusReadDao.countAgentWork2(info);
            msg.put("list",list);
            msg.put("status", true);
        }

    }



    /**
     * 下级代理商被投诉排名-汇总
     * @param info
     * @param msg
     */
    public void countAgentWorkCount(WorkCensusFilter info,Map<String, Object> msg) {
        //封装查询条件
        if(encapsulationConditionAgent(info,null,msg)){
            WorkCensusCount countInfo=workCensusReadDao.countAgentWorkCount(info);
            msg.put("countInfo",countInfo);
            msg.put("status", true);
        }
    }

    /**
     * 一级代理商被投诉排名-汇总
     * @param info
     * @param msg
     */
    public void countAgentWorkCount2(WorkCensusFilter info,Map<String, Object> msg) {
        //封装查询条件
        if(encapsulationConditionAgent(info,null,msg)){
            WorkCensusCount countInfo=workCensusReadDao.countAgentWorkCount2(info);
            msg.put("countInfo",countInfo);
            msg.put("status", true);
        }
    }




    /**
     * 下级代理商被投诉排名-导出
     * @param info
     * @param msg
     */
    @Override
    public void exportAgentWork(WorkCensusFilter info,HttpServletResponse response,Map<String, Object> msg) throws Exception{
        if(encapsulationConditionAgent(info,null,msg)){
            List<WorkCensusAgentInfo> list=workCensusReadDao.exportAgentWork(info);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss") ;
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月") ;

            String fileName = "下级代理商被投诉排名"+sdf.format(new Date())+".xlsx" ;
            String fileNameFormat = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameFormat);
            List<Map<String, String>> data = new ArrayList<Map<String,String>>() ;
            if(list.size()<1){
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("rank",null);
                maps.put("createTime",null);
                maps.put("agentName",null);
                maps.put("agentNo",null);
                maps.put("oneAgentNo",null);
                maps.put("oneAgentName",null);
                maps.put("agentLevel",null);
                maps.put("count",null);
                maps.put("dealResult2",null);
                maps.put("dealResult3",null);
                maps.put("dealResult4",null);
                data.add(maps);
            }else{
                for (WorkCensusAgentInfo item : list) {
                    Map<String, String> maps = new HashMap<String, String>();
                    maps.put("rank", item.getRank());
                    maps.put("createTime", item.getCreateTime()==null?"":sdf1.format(item.getCreateTime()));
                    maps.put("agentName",item.getAgentName());
                    maps.put("agentNo",item.getAgentNo());
                    maps.put("oneAgentNo",item.getOneAgentNo());
                    maps.put("oneAgentName",item.getOneAgentName());
                    maps.put("agentLevel",item.getAgentLevel());

                    maps.put("count",item.getCount());
                    maps.put("dealResult2",item.getDealResult2());
                    maps.put("dealResult3",item.getDealResult3());
                    maps.put("dealResult4",item.getDealResult4());
                    maps.put("oneAgentSaleName",item.getOneAgentSaleName());
                    data.add(maps);
                }
            }
            ListDataExcelExport export = new ListDataExcelExport();
            String[] cols = new String[]{"rank","createTime","agentName","agentNo","oneAgentNo","oneAgentName","agentLevel","count","dealResult2","dealResult3","dealResult4","oneAgentSaleName"};
            String[] colsName = new String[]{"排序","统计月份","所属代理商名称","所属代理商编号","一级代理商名称","一级代理商编号","代理商等级","投诉商户(总计)","投诉商户(已退款)","投诉商户(协商一致)","投诉商户(未处理)","对接经理"};
            OutputStream ouputStream =null;
            try {
                ouputStream=response.getOutputStream();
                export.export(cols, colsName, data, response.getOutputStream());
            }catch (Exception e){
                log.error("导出下级代理商被投诉排名失败!",e);
            }finally {
                if(ouputStream!=null){
                    ouputStream.close();
                }
            }

        }
    }

    /**
     * 一级代理商被投诉排名-导出
     * @param info
     * @param msg
     */
    @Override
    public void exportAgentWork2(WorkCensusFilter info,HttpServletResponse response,Map<String, Object> msg) throws Exception{
        if(encapsulationConditionAgent(info,null,msg)){
            List<WorkCensusAgentInfo> list=workCensusReadDao.exportAgentWork2(info);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss") ;
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月") ;

            String fileName = "一级代理商被投诉排名"+sdf.format(new Date())+".xlsx" ;
            String fileNameFormat = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameFormat);
            List<Map<String, String>> data = new ArrayList<Map<String,String>>() ;
            if(list.size()<1){
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("rank",null);
                maps.put("createTime",null);
                maps.put("oneAgentName",null);
                maps.put("oneAgentNo",null);
                maps.put("count",null);
                maps.put("dealResult2",null);
                maps.put("dealResult3",null);
                maps.put("dealResult4",null);
                maps.put("countPart",null);
                maps.put("oneAgentSaleName",null);
                data.add(maps);
            }else{
                for (WorkCensusAgentInfo item : list) {
                    Map<String, String> maps = new HashMap<String, String>();
                    maps.put("rank", item.getRank());
                    maps.put("createTime", item.getCreateTime()==null?"":sdf1.format(item.getCreateTime()));
                    maps.put("oneAgentName",item.getOneAgentName());
                    maps.put("oneAgentNo",item.getOneAgentNo());
                    maps.put("count",item.getCount());
                    maps.put("dealResult2",item.getDealResult2());
                    maps.put("dealResult3",item.getDealResult3());
                    maps.put("dealResult4",item.getDealResult4());
                    maps.put("countPart",item.getCountPart());
                    maps.put("oneAgentSaleName",item.getOneAgentSaleName());
                    data.add(maps);
                }
            }
            ListDataExcelExport export = new ListDataExcelExport();
            String[] cols = new String[]{"rank","createTime","oneAgentName","oneAgentNo","count","dealResult2","dealResult3","dealResult4","countPart","oneAgentSaleName"};
            String[] colsName = new String[]{"排序","统计月份","代理商名称","代理商编号","投诉商户(总计)","投诉商户(已退款)","投诉商户(协商一致)","投诉商户(未处理)","占比","对接经理"};
            OutputStream ouputStream =null;
            try {
                ouputStream=response.getOutputStream();
                export.export(cols, colsName, data, response.getOutputStream());
            }catch (Exception e){
                log.error("导出下级代理商被投诉排名失败!",e);
            }finally {
                if(ouputStream!=null){
                    ouputStream.close();
                }
            }

        }
    }




    /**
     * 封装查询必须条件
     * @param info
     * @param page
     */
    private boolean encapsulationConditionAgent(WorkCensusFilter info, Page<WorkCensusFilter> page, Map<String, Object> msg){
        if(!StringUtils.isNotBlank(info.getDateStrBegin()) || !StringUtils.isNotBlank(info.getDateStrEnd())){
            msg.put("status", false);
            msg.put("msg", "月份不能为空!");
            return false;
        }else{
            String[] str1s=info.getDateStrBegin().split("-");
            String[] str2s=info.getDateStrEnd().split("-");
            int month=(Integer.parseInt(str2s[0])-Integer.parseInt(str1s[0]))*12+(Integer.parseInt(str2s[1])-Integer.parseInt(str1s[1]));
            if(month>=6){
                msg.put("status", false);
                msg.put("msg","月份范围不能超过6个月");
                return false;
            }
            Date createTimeBegin=DateUtils.transformationTime(DateUtils.getDateMonFirstDay(DateUtils.format(info.getDateStrBegin(),"yyyy-MM")),1);
            Date createTimeEnd=DateUtils.transformationTime(DateUtils.getDateMonLastDay(DateUtils.format(info.getDateStrEnd(),"yyyy-MM")),2);
            info.setCreateTimeBegin(createTimeBegin);
            info.setCreateTimeEnd(createTimeEnd);
        }
        //获取组织
        getQueryTeamList(info,false);
        if(info.getTeamAllList().size()<=0){
            msg.put("status", false);
            msg.put("msg","统计组织为空");
            return false;
        }
        if(page!=null){
            info.setPageSize(page.getPageSize());
            info.setPageFirst(page.getFirst());
        }
        return true;
    }

}
